<template>
  <div>
    <!-- 项目详情弹框 -->
    <Modal draggable v-model="modal.projectDetial" title="项目详情" :footer-hide="true">
      <Form :model="formProjectDetial" :label-width="80">
        <FormItem label="项目名称" prop="name">
          <Input v-model="formProjectDetial.name" disabled></Input>
        </FormItem>
        <FormItem label="建设单位" prop="builder">
          <Input v-model="formProjectDetial.builder" disabled></Input>
        </FormItem>
        <FormItem label="公路等级" prop="roadlevel">
          <Input v-model="formProjectDetial.roadlevel" disabled></Input>
        </FormItem>
        <FormItem label="项目简称" prop="shortname">
          <Input v-model="formProjectDetial.shortname" disabled></Input>
        </FormItem>
        <FormItem label="线路名称" prop="linename">
          <Input v-model="formProjectDetial.linename" disabled></Input>
        </FormItem>
        <FormItem label="项目编码" prop="fullcode">
          <Input v-model="formProjectDetial.fullcode" disabled></Input>
        </FormItem>
      </Form>
    </Modal>
    <!-- 合同段详情弹框 -->
    <Modal draggable v-model="modal.htdDetial" title="施工合同段详情" :footer-hide="true">
      <Form :model="formHtdDetial" :label-width="80">
        <FormItem label="施工合同段" prop="name">
          <Input v-model="formHtdDetial.name" disabled></Input>
        </FormItem>
        <FormItem label="编码" prop="prefix">
          <Input v-model="formHtdDetial.prefix" disabled></Input>
        </FormItem>
        <FormItem label="起止桩号" prop="qqzh">
          <Input v-model="formHtdDetial.qqzh" disabled></Input>
        </FormItem>
        <FormItem label="施工单位" prop="sgdw_name">
          <Input v-model="formHtdDetial.sgdw_name" disabled></Input>
        </FormItem>
        <FormItem label="监理单位" prop="jldw_name">
          <Input v-model="formHtdDetial.jldw_name" disabled></Input>
        </FormItem>
      </Form>
    </Modal>
    <!-- 新增项目划分弹出框 -->
    <Modal draggable  :title="modalTitle" v-model="modal.treeAdd" :footer-hide="true">
      <Form
        ref="formAddTreeNode"
        :model="formAddTreeNode"
        :rules="formRule"
        :label-width="80"
      >
        <FormItem label="层级" prop="level">
          <Select
            v-model="formAddTreeNode.level"
            placeholder="单位工程/部位/分部/分项"
            filterable
            @on-change="changeSelect"
          >
            <Option
              v-for="(item, index) in selectList.levelArray"
              :value="item.id"
              :key="index"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="类型" prop="type">
          <Select
            v-model="formAddTreeNode.type"
            filterable
            placeholder="路面/路基/桥梁"
            ref="mySelect"
            @on-change="changeSelectType()"
          >
            <Option
              v-for="(item, index) of selectList.typeArray"
              :value="item.id"
              :key="index"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <div style="display:flex;justify-content: flex-start;">
          <FormItem style="width:50%;" label="编号" prop="code">
            <Input v-model="formAddTreeNode.code" disabled></Input>
          </FormItem>
          <FormItem :label-width="40" style="width:50%" prop="code1">
            <!-- <Input
              v-model="formAddTreeNode.code1"
              number
              placeholder="请填写编码"
            ></Input> -->
            <Input v-model="formAddTreeNode.code1" @on-change="handleSort(formAddTreeNode)"  placeholder="请填写编码" ></Input>
          </FormItem>
        </div>
        <FormItem label="名称" prop="name">
          <Input
            v-model="formAddTreeNode.name"
            placeholder="请填写名称"
          ></Input>
        </FormItem>
        <FormItem label="排序" prop="sort">
          <Select v-model="formAddTreeNode.sort" placeholder="1/2/3">
            <Option
              v-for="(item, index) of selectList.sortList"
              :value="item"
              :key="index"
              >{{ item }}</Option
            >
          </Select>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="submitformAdd(formAddTreeNode,'formAddTreeNode')"
            >保存</Button
          >
          <Button
            @click="resetformData('formAddTreeNode')"
            style="margin-left: 8px"
            >重置</Button
          >
        </FormItem>
      </Form>
    </Modal>
    <!-- 编辑项目划分弹出框 -->
    <Modal draggable :title="modalTitle" v-model="modal.treeEdit" :footer-hide="true">
      <Form
        ref="formEditTreeNode"
        :model="formEditTreeNode"
        :rules="formRule"
        :label-width="80"
      >
        <FormItem label="层级" prop="level">
          <Select
            v-model="formEditTreeNode.level"
            placeholder="单位工程/部位/分部/分项"
            filterable
            @on-change="changeSelect"
          >
            <Option
              v-for="(item, index) in selectList.levelArray"
              :value="item.id"
              :key="index"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="类型" prop="type">
          <Select
            v-model="formEditTreeNode.type"
            filterable
            placeholder="路面/路基/桥梁"
          >
            <Option
              v-for="(item, index) of selectList.typeArray"
              :value="item.id"
              :key="index"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <div style="display:flex;justify-content: flex-start;">
          <FormItem style="width:50%;" label="编号" prop="code">
            <Input v-model="formEditTreeNode.code" disabled></Input>
          </FormItem>
          <FormItem :label-width="40" style="width:50%" prop="code1">
            <Input
              v-model="formEditTreeNode.code1"
              number
              placeholder="请填写编码"
            ></Input>
          </FormItem>
        </div>
        <FormItem label="名称" prop="name">
          <Input
            v-model="formEditTreeNode.name"
            placeholder="请填写名称"
          ></Input>
        </FormItem>
        <FormItem label="排序" prop="sort">
          <Select v-model="formEditTreeNode.sort" placeholder="1/2/3">
            <Option
              v-for="(item, index) of selectList.sortList"
              :value="item"
              :key="index"
              >{{ item }}</Option
            >
          </Select>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="submitformEdit(formEditTreeNode,'formEditTreeNode')"
            >保存</Button
          >
          <Button
            @click="resetformData('formEditTreeNode')"
            style="margin-left: 8px"
            >重置</Button
          >
        </FormItem>
      </Form>
    </Modal>
    <!-- 查看项目划分弹出框/不可编辑 -->
    <Modal draggable :title="modalTitle" v-model="modal.treeView" :footer-hide="true">
      <Form
        ref="formEditTreeNode"
        :model="formEditTreeNode"
        :rules="formRule"
        :label-width="80"
      >
        <FormItem label="层级" prop="level">
          <Select
            v-model="formEditTreeNode.level"
            placeholder="单位工程/部位/分部/分项"
            @on-change="changeSelect"
            disabled
          >
            <Option
              v-for="(item, index) in selectList.levelArray"
              :value="item.id"
              :key="index"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="类型" prop="type">
          <Select
            v-model="formEditTreeNode.type"
            disabled
            placeholder="路面/路基/桥梁"
          >
            <Option
              v-for="(item, index) of selectList.typeArray"
              :value="item.id"
              :key="index"
              >{{ item.name }}</Option
            >
          </Select>
        </FormItem>
        <div style="display:flex;justify-content: flex-start;">
          <FormItem style="width:50%;" label="编号" prop="code">
            <Input v-model="formEditTreeNode.code" disabled></Input>
          </FormItem>
          <FormItem :label-width="40" style="width:50%" prop="code1">
            <Input v-model="formEditTreeNode.code1" number disabled></Input>
          </FormItem>
        </div>
        <FormItem label="名称" prop="name">
          <Input v-model="formEditTreeNode.name" disabled></Input>
        </FormItem>
        <FormItem label="排序" prop="sort">
          <Select v-model="formEditTreeNode.sort" disabled placeholder="1/2/3">
            <Option
              v-for="(item, index) of selectList.sortList"
              :value="item"
              :key="index"
              >{{ item }}</Option
            >
          </Select>
        </FormItem>
      </Form>
    </Modal>
    <!-- 确认删除对话框 -->
    <Modal v-model="modal.treeDelet" width="360">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>删除确认</span>
      </p>
      <div style="text-align:center">
        <p>
          确认删除后，此项数据会发生丢失。
        </p>
        <p>是否继续删除？</p>
      </div>
      <div slot="footer">
        <Button type="error" size="large" long @click="confirmDeleteTreeNode"
          >删除</Button
        >
      </div>
    </Modal>
  </div>
</template>
<script>
import apiObj from '@/api/project-partition.js';
import Bus from '../../../assets/eventbus/eventbus.js';

export default {
  name: 'modal',
  props: {
    htd: {
      // 合同段ID
      type: Object,
      htdId: 0
    },
    nodeId: {
      required: true
    },
    // 父节点Id
    parentId: {
      required: true
    },
    tree: {
      type: Object,
      required: true
    },
    currentLevel: Number
  },
  data () {
    return {
      modal: {
        // 项目详情弹框
        projectDetial: false,
        // 合同段详情弹框
        htdDetial: false,
        // 新增树节点弹框
        treeAdd: false,
        // 编辑树节点弹框
        treeEdit: false,
        // 查看树节点弹框
        treeView: false,
        // 删除树节点弹框
        treeDelet: false
      },
      // 项目详情表单
      formProjectDetial: {
        name: '',
        builder: '',
        roadlevel: '',
        shortname: '',
        linename: '',
        nfullcodeame: ''
      },
      // 合同段详情表单
      formHtdDetial: {
        name: '',
        prefix: '',
        qqzh: '',
        sgdw_name: '',
        linenajldw_nameme: ''
      },
      // 新增树节点的表单
      formAddTreeNode: {
        level: '',
        type: '',
        code: '',
        code1: '',
        name: '',
        sort: ''
      },
      // 编辑树节点的表单
      formEditTreeNode: {
        level: '',
        type: '',
        code: '',
        code1: '',
        name: '',
        sort: 0
      },
      // 判断是新增同级还是新增下级
      // 0 是新增同级 1和2是新增下级
      addTreeType: 0,
      // 表单验证
      formRule: {
        name: [
          { required: true, message: '请填写名称', trigger: 'blur' }
        ],
        level: [
          { required: true, message: '请选择层级', trigger: 'change', type: 'number' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change', type: 'number' }
        ]
      },
      // 弹框标头
      modalTitle: '',
      // 下拉框列表
      selectList: {
        // 层级下拉框列表
        levelArray: [],
        // 类型下拉框列表
        typeArray: [],
        // 排序下拉框列表
        sortList: []
      },
      selecDisable: true,
      fakerNodeId: -1,
      switchNodeId: -1, // 展开闭合的节点nodeId
      switchNodeExpand: null, // 展开闭合的节点expand
      dataMap: {} // tree数据map

    };
  },

  methods: {
    // 请求施工项目详情
    async viewProjectDetial () {
      this.modal.projectDetial = true;
      try {
        const resp = await apiObj.viewProjectDetails();
        this.formProjectDetial = resp.data.data;
      } catch (error) {}
    },
    // 请求施工合同段详情
    async viewHtdDetial (nodeId) {
      this.modal.htdDetial = true;
      let send = { nodeId: nodeId };
      try {
        const resp = await apiObj.viewContractDetails(send);
        this.formHtdDetial = resp.data.data;
      } catch (error) {}
    },
    // 获取编号的值，如果是数字，就填入默认排序
    handleSort (form) {
      if (Number.isInteger(Number(form.code1))) {
        this.$set(form, 'sort', Number(form.code1));
      }
    },
    // 新增树节点弹框事件
    showTreeNodeModal (type) {
      console.log('treetype', type);
      // 0是新增同级，1是新增下级
      this.addTreeType = type;
      this.modalTitle = '新增项目划分';
      this.modal.treeAdd = true;
      this.resetformData('formAddTreeNode');
      const level = type !== 0 ? this.currentLevel : this.currentLevel - 1;
      if ([3, 4, 6, 8].includes(level)) { // 为了针对"单位工程"，"分部工程"，"部位工程"，"分项工程"，这四个特殊情况
        this.$set(this.formAddTreeNode, 'level', level);
        console.log('进来没？');
        this.selectGetFixedNum(level);
        // this.handleSort(this.formAddTreeNode);
      }
      this.setSecondSelectLevel(level);

      let send = { parentId: this.parentId };
      this.getModalSelectList(send);
    },
    // 编辑树节点弹框事件
    editTreeNodeModal () {
      this.modalTitle = '编辑项目划分';
      let send = { nodeId: this.nodeId };
      this.editModalSelect(send);
      this.modal.treeEdit = true;

      // this.nodeId = nodeId
    },
    // 编辑弹框获取表单数据请求
    async editModalSelect (send) {
      let tree = this.tree.tree;
      this.newOldtreeConfigParameter(tree, send);
      if (tree === 'new') {
        try {
          const resp = await apiObj.editModalSelect(send);
          console.log('编辑弹框返回值', resp);
          const { levelnames, sorts, types, levelNameId, levelTypeId,
            prefix, code, nodeName, sort } = resp.data.data;
          this.selectList.levelArray = levelnames;
          this.selectList.sortList = sorts;
          this.selectList.typeArray = types;
          this.formEditTreeNode.level = levelNameId;
          this.formEditTreeNode.type = levelTypeId;
          this.formEditTreeNode.code = prefix;
          this.formEditTreeNode.code1 = code;
          this.formEditTreeNode.name = nodeName;
          this.formEditTreeNode.sort = sort;
          console.log(this.formEditTreeNode, 'this.formEditTreeNodethis.formEditTreeNodethis.formEditTreeNode');
        } catch (error) {}
      } else {
        try {
          const resp = await apiObj.editOldModalSelect(send);
          console.log('编辑弹框返回值', resp);
          const datas = resp.data.data;
          this.selectList.levelArray = datas.levelnames;
          this.selectList.sortList = datas.sorts;
          this.selectList.typeArray = datas.types;
          this.formEditTreeNode.level = datas.levelNameId;
          this.formEditTreeNode.type = datas.levelTypeId;
          this.formEditTreeNode.code = datas.prefix;
          this.formEditTreeNode.code1 = datas.code;
          this.formEditTreeNode.name = datas.nodeName;
          this.formEditTreeNode.sort = datas.sort;
        } catch (error) {}
      }
    },
    // 查看项目划分
    viewTreeNodeModal () {
      this.modalTitle = '查看项目划分';
      this.modal.treeView = true;
      let send = { nodeId: this.nodeId };
      this.editModalSelect(send);
    },
    // 请求获取新增/编辑弹框的下拉框值
    async getModalSelectList (send) {
      try {
        const resp = await apiObj.modalSelect(send);
        const datas = resp.data.data;
        // console.log('弹框出现返回值', resp);
        this.selectList.levelArray = datas.levelnames;
        this.selectList.sortList = datas.sorts;
      } catch (error) {
        console.log('error', error);
      }
    },
    // 选择层级下拉框事件
    changeSelect (levelId) {
      // console.log('点了？', levelId);
      this.setSecondSelectLevel(levelId);
      this.selectGetFixedNum(levelId);
    },
    // 新增项目划分选择完类型，名称项对应展示
    changeSelectType () {
      // this.$set(this.formAddTreeNode, 'name', this.$refs.mySelect.query);
      this.formAddTreeNode.name = (this.selectList.typeArray.find(
        i => i.id == this.formAddTreeNode.type
      )).name;
    },
    // 选完一级层级（单位工程，分部工程这些），获取二级列表内容
    async setSecondSelectLevel (levelId) {
      // console.log('this.nodeId', this.nodeId);
      if (!levelId) {
        return;
      }
      const send = { levelNameId: levelId, parentId: this.nodeId };
      try {
        const resp = await apiObj.getSecondLevel(send);
        this.selectList.typeArray = resp.data.data;
        // this.selecDisable = false;
      } catch (error) {}
    },
    // 层级下拉事件触发获取固定编号请求
    async selectGetFixedNum (levelId) {
      const send = { nodeType: levelId, parentId: this.nodeId };
      try {
        const resp = await apiObj.selectTonum(send);
        const { prefix, code } = resp.data.data;
        this.formAddTreeNode.code = prefix;
        this.formAddTreeNode.code1 = code;
        this.handleSort(this.formAddTreeNode);
        // console.log('固定编号', resp);
      } catch (error) {}
    },

    // 操作成功后，根据合同段Id刷新项目树
    async refreshContractTree () {
      let tree = this.tree.tree;
      let send = {
        nodeId: this.htd.htdId
      };
      if (tree === 'new') {
        try {
          const resp = await apiObj.getContractTree(send);
          const datas = resp.data.data;
          // 给新树重新赋值
          this.tree.newTree = datas;
          this.tree.newTree = this.switchTreeNodeExpand(this.nodeId, datas);
          console.log(6666, this.tree.newTree);
        } catch (error) {
          console.error(error);
        }
      } else {
        try {
          const resp = await apiObj.getContractOldTree(send);
          const datas = resp.data.data;
          this.tree.oldTree = this.switchTreeNodeExpand(this.nodeId, datas);
          // this.tree.oldTree = datas;
        } catch (error) {}
      }
    },
    switchExpand (map) {
      this.dataMap = map;
    },
    // 树的展开闭合状态
    switchTreeNodeExpand (nodeId, treeData) {
      if (nodeId == undefined || nodeId == null) {
        nodeId = this.fakerNodeId;
      }
      const map = this.dataMap;
      // let index = this.findTop(this.getUrlListFn(treeData), nodeId);
      const handleTerrData = tree => {
        tree.forEach(node => {
          for (let key in map) {
            if (node.nodeId == key) {
              this.$set(node, 'expand', map[key]);
              // node.expand = map[key];
            }
          }
          // node.expand = true;
          if (node) {
            if (node.children) {
              handleTerrData(node.children);
            }
          }
        });
      };
      // handleTerrData([treeData[index]]);
      handleTerrData(treeData);
      // console.log('treeDate+++', treeData);
      return treeData;
    },
    // 获取nodeId在treeData那一层位置，然后把该层全部展开（目前没有更优化的方法，暂时用这个）
    // getUrlListFn (data) {
    //   const res = [];
    //   for (let i = 0; i < data.length; i++) {
    //     res.push(this.deepFirst([data[i]]));
    //   }
    //   return res;
    // },

    // deepFirst (data, result = []) {
    //   for (let i = 0; i < data.length; i++) {
    //     result.push(data[i].nodeId);
    //     data[i].children &&
    //       data[i].children.length &&
    //       this.deepFirst(data[i].children, result);
    //   }
    //   return result;
    // },

    // // 找顶点
    // findTop (data, nodeId) {
    //   let res = null;
    //   for (let i = 0; i < data.length; i++) {
    //     if (data[i].includes(nodeId)) {
    //       res = i;
    //       break;
    //     } else if (data[i].includes(this.fakerNodeId)) {
    //       res = i;
    //       break;
    //     } else {
    //     }
    //   }
    //   return res;
    // },
    // 获取nodeId在treeData那一层位置，结束

    handleResetform (form) {
      this.$refs['formAddTreeNode'].resetFields();
    },
    // 提交新增树节点表单数据
    async submitformAdd (form, name) {
      let tree = this.tree.tree;
      let type = this.addTreeType;
      const send = {
        cj_type: form.type,
        code: form.code1,
        sort: form.sort,
        nodeName: form.name,
        nodeType: form.level
      };
      if (type === 0) {
        // 新增同级
        send.parentId = this.parentId;
      } else {
        send.parentId = this.nodeId;
      }
      this.newOldtreeConfigParameter(tree, send);
      if (tree === 'new') {
        // 新树的新增
        console.log('新树');
        try {
          this.$refs[name].validate(async (valid) => {
            if (valid) {
              // 新树的新增
              await apiObj.addTreeNode(send);
              this.handleResetform(form);
              this.refreshContractTree(); // 请求完毕之后重新刷一下树
              this.modal.treeAdd = false;
            } else {
              this.$Message.error('请完善表单');
            }
          });
        } catch (error) {}
      } else {
        // 旧树的新增
        console.log('旧树');
        try {
          this.$refs[name].validate(async (valid) => {
            if (valid) {
              // 新树的新增
              await apiObj.addOldTreeNode(send);
              this.handleResetform(form);
              this.refreshContractTree(); // 请求完毕之后重新刷一下树
              this.modal.treeAdd = false;
            } else {
              this.$Message.error('请完善表单');
            }
          });
        } catch (error) {}
      }
    },

    // 提交编辑树节点表单数据
    async submitformEdit (form, name) {
      let tree = this.tree.tree;
      let type = this.addTreeType;
      console.log('type', type);
      const send = {
        cj_type: form.type,
        code: form.code1,
        sort: form.sort,
        nodeName: form.name,
        nodeType: form.level,
        nodeId: this.nodeId
      };
      this.newOldtreeConfigParameter(tree, send);
      if (tree === 'new') {
        // 新树的新增
        try {
          this.$refs[name].validate(async (valid) => {
            if (valid) {
              // 新树的新增
              await apiObj.editTreeNodeSubmit(send);
              this.refreshContractTree(); // 请求完毕之后重新刷一下树
              this.modal.treeEdit = false;
            } else {
              this.$Message.error('请完善表单');
            }
          });
        } catch (error) {}
      } else {
        // 旧树的新增
        console.log('旧树');
        try {
          this.$refs[name].validate(async (valid) => {
            if (valid) {
              // 新树的新增
              let resp = await apiObj.editOldTreeNodeSubmit(send);
              console.log('请求之后的返回值', resp);
              this.refreshContractTree(); // 请求完毕之后重新刷一下树
              this.modal.treeEdit = false;
            } else {
              this.$Message.error('请完善表单');
            }
          });
        } catch (error) {}
      }
    },

    // 根据新旧树，操作树节点时，配置不同的提交参数。
    newOldtreeConfigParameter (tree, send) {
      // 旧树的所有操作都多传一个合同段参数
      // 对新树进行配置参数
      switch (tree) {
        case 'old':
          send['htdId'] = this.htd.htdId;
          break;
        default:
          break;
      }
    },

    // 表单重置按钮
    resetformData (name) {
      this.$refs[name].resetFields();
    },
    // 删除节点弹框
    deleteTreeNodeModal (node) {
      this.fakerNodeId = node.parentId;// 删除时保留该节点的父节点ID。即parentID
      this.modal.treeDelet = true;
    },
    // 确认删除
    async confirmDeleteTreeNode () {
      let tree = this.tree.tree;
      const send = { nodeId: this.nodeId };
      this.newOldtreeConfigParameter(tree, send);
      if (tree === 'new') {
        try {
          const resp = await apiObj.deleteTreeNode(send);
          console.log('新树删除了？', resp);
          this.refreshContractTree();
          this.modal.treeDelet = false;
        } catch (error) {
          console.log('error', error);
        }
      } else {
        try {
          const resp = await apiObj.deleteOldTreeNode(send);
          console.log('旧树删除了？', resp);
          // throw new Error('老铁我错了吗？');
          this.refreshContractTree();
          this.modal.treeDelet = false;
        } catch (error) {
          console.log('error', error);
        }
      }
    }
  },
  mounted () {
    console.log('this.parentId', this.parentId);
    Bus.$on('viewProjectDetial', this.viewProjectDetial);
    Bus.$on('viewHtdDetial', this.viewHtdDetial);
  }

  // 拿到传过来的 是否显示 和 对应的id,去请求
};
</script>
<style></style>
